import { login, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // user login
  Login({ commit }, userInfo) {
    const username = userInfo.username.trim()
    const password = userInfo.password
    // const code = userInfo.code
    // const uuid = userInfo.uuid
    const code = ''
    const uuid = ''
    return new Promise((resolve, reject) => {
      login(username, password, code, uuid)
        .then(response => {
          commit('SET_TOKEN', response.data.token)
          setToken(response.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  GetUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const responseData = response.data
        const user = responseData.user
        if (responseData.roles && responseData.roles.length > 0) {
          commit('SET_ROLES', responseData.roles)
          commit('SET_PERMISSIONS', responseData.permissions)
        } else {
          commit('SET_ROLES')
        }
        commit('SET_NAME', user.username)
        commit('SET_AVATAR', user.avatar)

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  Logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken()
        commit('SET_TOKEN', '')
        commit('RESET_STATE')
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  FedLogLout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
